<?php

namespace App\Services;

use EasyWeChat\MiniApp\Application;
use Nette\Utils\DateTime;
use TheSeer\Tokenizer\Exception;

class EasyWechatService
{

    private static function getConfig() : array
    {
        return [
            'app_id' => config('services.wechat.app_id'),
            'secret' => config('services.wechat.app_secret'),
            'use_stable_access_token' => true
        ];
    }

    public static function analysisIdCard(string $type, string $path) : array
    {
        $app = new Application(self::getConfig());

        $api = $app -> getClient();

        if(config('app.env') == 'local') {
            $url = $type == 'Front' ? 'https://static.shuwentong.com/uploads/user/1124/20250314/202503141302072db842749.jpg' : 'https://static.shuwentong.com/uploads/user/1124/20250314/20250314130216e01895972.jpg' ;
        } else {
            $url = $path;
        }

        $response = $api -> post('/cv/ocr/idcard',  [
                'img_url' => $url, // HTTPS公网图片
        ]) -> toArray();

        if($response['errcode'] !== 0) {
            throw new Exception($response['errmsg']);
        }

        if($response['type'] !== $type) {
            throw new Exception('类型错误');
        }
        $fullPath = parse_url($url, PHP_URL_PATH);

        if($response['type'] == "Front") {
            $data = [
                'type'          => 'front',
                'path'          => $fullPath,
                'name'          => $response['name'],
                'card_no'       => $response['id'],
                'address'       => $response['addr'],
                'gender'        => $response['gender'] == "男" ? 1 : 0,
                'nationality'   => $response['nationality'],
                'birth'         => $response['birth']
            ];
        }

        if($response['type'] == "Back") {
            $date = explode('-', $response['valid_date']);

            $data[1] = $date[1] == '长期' ? '20991231' : $date[1];

            $start_date = DateTime::createFromFormat('Ymd',$date[0])->format('Y-m-d');

            $end_date = DateTime::createFromFormat('Ymd',$date[1])->format('Y-m-d');

            $data = [
                'type'          => 'back',
                'path'          => $fullPath,
                'start_date'    => $start_date,
                'end_date'      => $end_date,
                'authority'     => $response['authority']
            ];
        }

        return $data;
    }
}
